package com.example.controller;

import com.example.common.IdWorker;
import com.example.common.R;
import com.example.domain.User;
import com.example.service.UserService;
import com.example.utils.SMSUtils;
import com.example.utils.ValidateCodeUtils;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@RestController
@ResponseBody
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session)
    {
        String phone = user.getPhone();//获取电话
        log.info(phone);
        if(StringUtils.isNotEmpty(phone))//判断不为空
        {
            String code = String.valueOf(ValidateCodeUtils.generateValidateCode(4));//生成四位验证码
            log.info("验证码发送成功："+code);
            //SMSUtils.sendMessage("冯凯隆","SMS_268555298",phone,code);//调用阿里云的api发送短信
            session.setAttribute(phone,code);//把验证码保存
            return R.success("验证码发送成功");
        }
        log.info("验证码发送失败");
       return R.error("验证码未收到");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session)
    {
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        String codeSession = session.getAttribute(phone).toString();
        if(code.equals(codeSession))
        {
            User user=new User();
            if(userService.selectbyphone(phone)==null)
            {
                user.setId(new IdWorker().nextId());
                user.setPhone(phone);
                user.setStatus(1);
                userService.savephone(user);
            }
            User selectbyphone = userService.selectbyphone(phone);
            session.setAttribute("user",selectbyphone.getId());
            return R.success(user);
        }
        else
        {
            return R.error("验证码错误");
        }
    }

    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session)
    {
        session.removeAttribute("user");
        return R.success("退出成功");
    }

}
